import { defineStore } from "pinia"
import { getResourceUrl, loginJumpUrl } from '@/api'
import { getTreeData } from '@/uilts'
import router from "@/router"
const userStore = defineStore('userStore', {
  state: () => {
    return {
      userInfo: JSON.parse(localStorage.getItem('GXTY_USER_INFO')) || null,
      menuList: [],
      code: '450010',
      iframeUrl: null,
      defaultMenu: null
    }
  },
  actions: {
    //  储存用户信息
    setUserInfo(value) {
      localStorage.setItem('GXTY_USER_INFO', JSON.stringify(value))
      this.userInfo = value
    },
    //  从其它系统过来登录
    async loginJumpUrlAjax(token) {
      const { data } = await loginJumpUrl(token, this.code)
      this.setUserInfo(data)
      this.getMenuList()
    },
    //  获取用户资源信息
    async getMenuList() {
      try {
        const { data } = await getResourceUrl(this.code)
        this.menuList = getTreeData(
          data,
          "code",
          "parentCode",
          "children",
          "-1"
        )
        const item = this.menuList[0]
        if (item.url) {
          this.iframeUrl = item.url
          this.defaultMenu = item.code
        } else if (!item.url && item.children) {
          this.iframeUrl = item.children[0].url
          this.defaultMenu = item.children[0].code
        }
      } catch (error) {
        console.log(error);
      }
    },
    //  跳登录页面
    loginOut() {
      router.push({ path: '/' })
    }
  },
  getters: {}
})

export default userStore